import api from '../../api/api.js';
import db from '../../utils/db.js';
import { unlockEpisode, isNullOrEmpty } from '../../utils/util.js';
import { RewardedVideoAd } from '../../utils/rewarded-video-ad.js';
import { InterstitialAd } from '../../utils/interstitial-ad.js';
const { PlayletExtension, getPlayletManager } = tt;
const app = getApp();
const os = app.os;

PlayletExtension({
  pm: undefined,
  videoAd: undefined,
  openAdNum: 0,
  option: {},
  isPlay: false,
  isLoadData: false,
  data: {
    iaaMix: app.globalData.iaaMix,
    isOpanAd: false,
    isSlide: false,
    showBingeTips: true,
    currentTime: 0,
    duration: 0,
    fromPlayletId: 0,
    fromPlayletData: {
      albumId: 0,
      playletId: 0,
      rAlbumId: 0
    },
    currentAblum: false, //剧集信息和列表
    currentVideo: false, // 当前播放集信息
  },
  methods: {

    onLoad(option) {
      app.echo("播放页参数: ", option);
      this.option = option;
    },

    onReady() {
      const _this = this;
      const pm = getPlayletManager(this);
      this.pm = pm;

      this.bindOtherEvents();
      this.bindVideoEvents();

      // 加载剧集信息
      if (app.globalData.userInfo !== '') {
        _this.refreshChapterData();
      } else {
        _this.initTime = setInterval(function() {
          if (app.globalData.userInfo !== '') {
            clearInterval(_this.initTime);
            _this.refreshChapterData();
          }
        },500);
      }

      // 播放心跳
      this.playTimerId = setInterval(function(){
        if (_this.isPlay) {
          _this.sendAppLogs('video', 3);
        }
      }, 10000);

    },

    onShow() {
      
    },

    onHide() {

    },

    /**
     * 绑定其他事件
     */
    bindOtherEvents() {
      // 绑定充值面板充值成功事件
      app.eventer.on('onRechargeSuccess', this.onRechargeSuccess.bind(this));

      // 绑定充值面板充值取消事件
      app.eventer.on('onRechargeCancel', this.onRechargeCancel.bind(this));

      // 绑定挽留弹框取消事件
      app.eventer.on('onPopCancel', this.onPopCancel.bind(this));

      // 绑定挽留弹框成功事件
      app.eventer.on('onPopSuccess', this.onPopSuccess.bind(this));
      
      // 绑定点击其他事件
      app.eventer.on('onAdUnlockEvent', this.onAdUnlockEvent.bind(this));
    },

    /**
     * 绑定播放器事件
     */
    bindVideoEvents() {
      const _this = this;
      const pm = this.pm;
      
      // 视频播放
      pm.onPlay((e) => {
        app.echo("触发开始播放onPlay回调:" , JSON.stringify(e,null,2));
        this.getCurrentVideo(e.seq);
        this.isPlay = true;

        if(e.seq == 1){
          setTimeout(() => {
            this.showInterstitialAd();
          }, 30000);
        }

        this.andSeenPlaylet();
      });

      // 退出挽留推荐
      if (os.canIUse('back-recommend')) {
        pm.setRecommendConfig({
          entryType: 2 ,
          switchStatus: true,
          data:[]
        });
      }

      // 视频暂停
      pm.onPause((e) => {
        app.echo("触发暂停播放onPause回调:" , JSON.stringify(e,null,2));
        this.getCurrentVideo(e.seq);
        this.isPlay = false;
        this.sendAppLogs('video', 4);
        this.showInterstitialAd();
      });

      // 视频结束
      pm.onEnded((e) => {
        app.echo("触发播放到末尾onEnded回调:" , JSON.stringify(e,null,2));
        this.getCurrentVideo(e.seq);
        this.isPlay = false;
        this.sendAppLogs('video', 2); 
      });
      
      // 视频出错
      pm.onError((e) => {
        app.echo("触发视频出错onError回调:" , JSON.stringify(e,null,2));
        this.getCurrentVideo(e.seq);
        this.sendAppLogs('video', 16, {
          method_mark: JSON.stringify(e),
          method_mark_1: e.errNo
        });
      });

      // 播放进度
      pm.onTimeUpdate((e) => {
        // app.echo("触发播放进度变化onTimeUpdate回调:" , JSON.stringify(e,null,2));
        Object.assign(this.data, e);
        if (this.data.isSlide) {
          const currentVideo = this.getCurrentVideo(e.seq);
          if (this.data?.lastcurrentTime === currentVideo?.currentTime) {
            return;
          }
          this.data.isSlide = false;
          this.sendAppLogs('video', 10, {
            method_mark: this.data?.lastcurrentTime || 0,
            method_mark_1: currentVideo?.currentTime || 0
          });
        }
      });

      // 视频倍速改变
      pm.onPlayBackRateChange((e) => {
        app.echo("触发视频倍速onPlayBackRateChange回调:" , JSON.stringify(e,null,2));
        this.getCurrentVideo(e.seq);
        this.sendAppLogs('video', 15, {
          method_mark_1: e.playbackRate.toString()
        });
      })

      // 点击解锁按钮
      pm.onClickUnlock((e) => {
        app.echo("触发点击解锁按钮onClickUnlock回调:" , JSON.stringify(e,null,2), this.data);
        this.getCurrentVideo(e.seq);
        this.goAutoUnlock();
      });

      // 加桌相关能力回调
      pm.onAddShortCut((e) => {
        // app.echo("触发开始播放onAddShortCut回调:" , JSON.stringify(e,null,2));
        this.sendAppLogs('app', 4, {
          method_mark: 'addShortcut',
          method_mark_1: '加至桌面'
        });
      });

      // 切换剧集
      pm.onChangeEpisode((e) => {
        app.echo("触发选集切换onChangeEpisode回调:", JSON.stringify(e, null, 2));
        let currentVideo = this.data.currentVideo;
        this.openAdNum = 0;

        switch (e.scene) {
          case "swipe_next":
            this.sendAppLogs('video', 11, {
              method_mark_1: currentVideo?.num || 1
            });
            break;

          case "seq_select":
            this.sendAppLogs('video', 12, {
              method_cid: currentVideo?.num || 1,
              method_mark_1: e.seq
            });
            break;

          case "first_play":
            
            break;

          case "recommend":
            const { fromPlayletData } = this.data;
            Object.assign(this.option, {
              tt_album_id: e.albumId,
              playlet_id: 0
            });

            if (fromPlayletData.rAlbumId > 0 && fromPlayletData.rAlbumId == e.albumId) {
              this.data.fromPlayletId = fromPlayletData.playletId;
            } else {
              this.data.fromPlayletId = 0;
            }

            Object.assign(this.data.fromPlayletData, {
              albumId: 0,
              playletId: 0,
              rAlbumId: 0
            });

            this.refreshChapterData();
            break;
        
          default:
            break;
        }

        if (e.scene !== "recommend") {
          currentVideo = this.getCurrentVideo(e.seq);
          this.goAutoUnlock();
          
          if (currentVideo?.follow === currentVideo?.num && currentVideo?.is_collect === 0 && currentVideo?.is_unlock === 0 && this.data.showBingeTips) {
            setTimeout(function(){
              _this.openCustomDialog(6);
            }, 2000);
          }
        }

        // 分享参数设置
        if (currentVideo !== false) {
          pm.setConfig({
            shareParam: {
              title: currentVideo.playlet_name,
              desc: "",
              path: `pages/player/player?tt_album_id=${e.albumId}&tt_episode_id=${e.episodeId}&playlet_id=${currentVideo.playlet_id}&playlet_num=${currentVideo.num}`,
              imageUrl: currentVideo.cover_img,
              templateId: ""
            }
          });
        }
      });

      // 点击控件
      pm.onControlTap((e) => {
        app.echo("触发点击控件onControlTap回调:" , JSON.stringify(e,null,2))
        const _this = this;
        // const lastVideo = this.data.currentVideo;
        const currentVideo = this.getCurrentVideo(e.seq);
        
        switch (e.controlType) {
          case "play":
            this.sendAppLogs('video', 5);
            break;

          case "share":
            break;

          case "pause":
            break;

          case "openCatalog":
            break;

          case "progress":
            this.data.lastcurrentTime = currentVideo?.currentTime || 0;
            this.data.isSlide = true;
            break;

          case "subscribe":
            if(currentVideo.is_collect === 0){
              app.addAndDelCollect(currentVideo, function(res){
                _this.updateCollectUpdated(res);
                _this.openCustomDialog(5);
              });
            }
            break;

          case "unsubscribe":
            if(currentVideo.is_collect > 0){
              app.addAndDelCollect(currentVideo, function(res){
                _this.updateCollectUpdated(res);
              });
            }
            break;

          case "like":
            this.sendAppLogs('video', 8);
            break;

          case "unlike":
            this.sendAppLogs('video', 9);
            break;
        
          default:
            this.sendAppLogs('app', 4, {
              method_mark: e.controlType
            });
            break;
        }
      });
    },

    /**
     * 绑定剧集试看功能
     */
    bindUnlockPreview(){
      const _this = this;
      const pm = this.pm;
      // 判断API是否可用，onUnlockPreviewButtonClick支持时，所有API均可使用
      if (app.playerData.isUnlockPreview) {

        if (app.globalData.appType !== 1) {
          return;
        }

        const unlockNum = this.data.currentAblum?.ad_unlock_num || 1;
        pm.setUnlockPreview({
          second: 5,
          description: `恭喜获得免费看剧福利，看广告免费解锁${unlockNum}集！`,
          buttons: [{
            id: 'leftBtn',
            text: this.data.iaaMix ? '免广告解锁':'下次再看',
          }, {
            id: 'rightBtn',
            text: '{x}s后拉起广告',
          }]
        })

        // 设置右侧试看倒计时按钮，倒计时结束后的文案，注意text不能超过10个字
        pm.setUnlockPreviewButton('rightBtn', {
          text: '看广告解锁'
        });
        
        // 按钮点击
        pm.onUnlockPreviewButtonClick((data) => {
          app.echo('onUnlockPreviewButtonClick', data);
          const { triggerButtonId, seq, albumId } = data;
          if (triggerButtonId === 'rightBtn') {
            _this.onAdUnlockEvent({type: 1});
          }
          
          if (triggerButtonId === 'leftBtn') {
            if (this.data.iaaMix) {
              _this.onAdUnlockEvent({type: 2});
            } else {
              // _this.onAdUnlockEvent({type: 1});
            }
          }
          
          _this.data.isOpanAd = true;
          setTimeout(function(){
            _this.data.isOpanAd = false;
          }, 6000);

        });
        
        // 试看倒计时结束
        pm.onPreviewEnd((e) => {
          _this.onAdUnlockEvent({type: 1});
        })
      }
    },

    /**
     * 检查并选择解锁方式
     */
    goAutoUnlock() {
      const currentVideo = this.data.currentVideo;
      if (currentVideo === false) {
        return;
      }

      if (currentVideo.is_unlock == 0 || currentVideo.num <= 5) {
        return;
      }

      // 扣币解锁
      if (app.globalData.appType === 2) {
        this.coinUnlockPlaylet();
        return;
      }
    },

    /**
     * 充值成功
     */
    onRechargeSuccess(res) {
      app.echo("onRechargeSuccess", res)
      const _this = this;
      const { cData } = res;

      if (cData.gear_type_id === 1) {
        this.coinUnlockPlaylet();
        return;
      }

      if (cData.gear_type_id === 2) {
        this.updateUnlockVideo(2);
        app.refreshUserInfo((data)=>{
          if (data.is_vip) {
            // _this.updateUnlockVideo(2);
          }
        });
      }

      if (cData.gear_type_id === 3) {
        this.updateUnlockVideo(3);
      }
    },

    /**
     * 取消充值弹框
     */
    onRechargeCancel(res) {
      app.echo("onRechargeCancel", res)
      const { pData } = res;
      this.openPayRetainDialog(pData?.gear_id || 0);
    },

    /**
     * 挽留弹窗确定事件
     */
    onPopSuccess(res) {
      app.echo("onPopConfirm", res)
      const { type, data } = res;
      if (type === 'adFreeUnlock') {
        this.coinUnlockPlaylet();
        return;
      }
      
      if (type == 1) {
        this.openRewardedVideoAd(4, data.unlock_num);
        return;
      }
      
      if (type == 2) {
        
        if (data.gear_type_id === 1) {
          this.coinUnlockPlaylet();
          return;
        }

        if (data.gear_type_id === 2) {
          this.updateUnlockVideo(2);
          app.refreshUserInfo((data)=>{
            if (data.is_vip) {
              // this.updateUnlockVideo(2);
            }
          });
        }
    
        if (data.gear_type_id === 3) {
          this.updateUnlockVideo(3);
        }
        return;
      }

      if (type == 4) {
        this.openRewardedVideoAd(4, data.unlock_num);
        return;
      }
    },

    /**
     * 挽留弹窗取消事件
     */
    onPopCancel(res) {
      app.echo("onPopCancel", res);
      const { type } = res;
      if (type == 1) {
        
      }
      if (type == 2) {
        this.openAdRetainDialog();
      }
    },
    
    /**
     * 打开付费挽留弹框
     */
    openPayRetainDialog(gearId = 0){
      api.getRetainConfig({
        playlet_id: this.data.currentVideo?.playlet_id || 0,
        is_free: 1, 
        gear_id: gearId
      }, {showErr: false}).then(res => {
        if (res.code == 200 && !isNullOrEmpty(res.data)) {
          this.openCustomDialog(2, res.data);
        } else {
          this.openAdRetainDialog();
        }
      });
    },

    /**
     * 打开广告挽留弹框
     */
    openAdRetainDialog(){
      if (!this.isCanUnlock()) {
        return;
      }
      api.getRetainConfig({
        playlet_id: this.data.currentVideo?.playlet_id || 0,
        is_free: 2, 
        gear_id: 0
      }, {showErr: false}).then(res => {
        if (res.code == 200 && !isNullOrEmpty(res.data)) {
          this.openCustomDialog(3, res.data);
        }
      });
    },

    /**
     * 打开自定义弹窗
     */
    openCustomDialog(type, data = {}) {
      app.playerData.dialogType = type;
      if (type === 1) {
        app.playerData.currentVideo = data;
      }

      if (type === 2 || type === 3 || type === 7) {
        app.playerData.retainData = data;
        app.playerData.currentVideo = this.data.currentVideo;
      }

      if (this.pm) {
        this.pm.toggleCustomDialog('open');
      }
    },

    /**
     * 点击广告事件
     */
    onAdUnlockEvent(res) {
      app.echo("onAdUnlockEvent", res);
      const { type } = res;
      const _this = this;
      // 打开广告
      if (type === 1) {
        this.clearBenAdTimer();
        if (!this.isCanUnlock()) {
          app.Tips({title: '不可跳集解锁'});
          return;
        }
        this.openRewardedVideoAd();
        return;
      }
      // 免广告解锁
      if (type === 2) {
        this.clearBenAdTimer();
        this.coinUnlockPlaylet();
        return;
      }
      // 试看当前视频
      if (type === 3) {
        this.pm.setCurrentUnlock();
        return;
      }
      // 更新解锁状态
      if (type === 4) {
        this.refreshChapterUnlock();
        return;
      }
      // 点击返回按钮
      if (type === 5) {
        this.onClickBack();
        return;
      }
      // 关闭长按倍速提示弹框
      if (type == 'closeLongspeedTips') {
        db.set('show_longspeed_tips', 1);
        return;
      }
      // 关闭追剧提示
      if (type == 'bingeTips') {
        this.data.showBingeTips = false;
        return;
      }
      // 福利广告解锁
      if (type == 'showBenefitAd') {
        this.bAdTimerId = setTimeout(function(){
          if (_this.isCanUnlock()) {
              _this.openCustomDialog(7, {unlock_num: res.data.chapter_unlock_num});
          }
        }, 3000);
        return;
      }
    },

    /**
     * 清除福利弹窗
     */
    clearBenAdTimer(){
      if (this?.bAdTimerId > 0) {
        clearInterval(this.bAdTimerId);
        this.bAdTimerId = 0;
      }
    },

    /**
     * 点击返回
     */
    onClickBack(){
      let currentVideo = this.getCurrentVideo();
      if (currentVideo?.is_collect == 0) {
        os.showModal({
          title: "加入追剧防止丢失",
          content: "下次观看即可快速找到，请点击右下角「追剧」",
          confirmText: "好的",
          cancelText: "关闭",
          confirmColor: "#f25c40",
          success(res) {
            if (!res.confirm) {
              app.goBack();
            } 
          }
        });  
      } else {
        app.goBack();
      }
    },

    /**
     * 是否可解锁
     */
    isCanUnlock() {
      let { currentVideo, seq, currentAblum } = this.data;
      if (app.globalData.appType === 2) {
        return true;
      }
      if (currentAblum === false) {
        return false;
      }
      seq = seq - 1;
      if (seq <= 0) {
        return false;
      }
      currentVideo = currentAblum.list.find(item => item.num === seq);
      if (currentVideo !== undefined) {
        if (currentVideo.is_unlock === 0) {
          return true;
        }
      }
      return false;
    },

    /**
     * 打开激励视频广告
     * @param unlockType 0=剧集广告解锁,4=弹窗广告解锁
     * @param unlockNum  解锁集数
     */
    openRewardedVideoAd(unlockType = 0, unlockNum = 1){
      const _this = this;
      let { currentVideo,isOpanAd } = this.data;

      if (currentVideo?.is_unlock === 0) {
        return;
      }

      if (isOpanAd) {
        return;
      }

      _this.unlockNum = unlockNum;
      _this.unlockType = unlockType;

      if (this.videoAd !== undefined) {
        this.videoAd.destroy();
        setTimeout(function(){
          _this.videoAd.show();
        }, 50);
        return;
      }
  
      this.videoAd = new RewardedVideoAd({
        // adConfList: app.globalData.adverConfig,
        onAdConfChange: (res) => {
          if (res.type === 1) {
            app.setGlobalData('adverConfig', res.data);
          } else {
            app.setGlobalData('currentAdConf', res.data);
          }
        },
        onLoad: (res) => {
          if(res.type === 'success'){
            _this.sendAppLogs('iaa', 2, {
              method_mark: '加载成功',
              method_mark_1: 200
            });
          }
          if(res.type === 'reg'){
            _this.sendAppLogs('iaa', 1);
          }
        },
        onShow: () => {
          _this.sendAppLogs('iaa', 4);
        },
        onClose: (res) => {
          if (res.isEnded) {
            _this.updateUnlockVideo(_this.unlockType, _this.unlockNum);
            _this.sendAppLogs('iaa', 6, {
              method_mark: 1, 
              method_mark_1: res.second
            });
          } else {
            app.Tips({title: '未观看完视频，无法获得奖励'});
            _this.sendAppLogs('iaa', 6, {
              method_mark: 0, 
              method_mark_1: res.second
            });
            
            // 挽留弹框
            if (app.globalData.appType !== 2) {
              if (_this.openAdNum < 2) {
                _this.openAdNum++;
                app.eventer.emit('onPlayerPageEvent', {type: 'closeAd'});
              } else {
                _this.openAdRetainDialog();
              }
            }
            
          }
        },
        onError:(error) => {
          if (error.errCode === -2) {
            app.Tips({title: '操作太频繁，请稍后重试'});
          } else {
            app.Tips({title: '拉取广告失败，请稍后重试'});
          }
          _this.sendAppLogs('iaa', 3, {
            method_mark: error.errMsg || '', 
            method_mark_1: error.errCode || ''
          });
        }
      });
    },

    /**
     * 显示插屏广告
     */
    showInterstitialAd(){
      const { currentVideo } = this.data;
      if (currentVideo === false) {
        return;
      }
      if (currentVideo.is_unlock !== 0) {
        return;
      }
      app.showInterstitialAd({
        method_id: currentVideo.playlet_id, 
        method_cid: currentVideo.num,
      });
    },

    /**
     * 销毁插屏广告
     */
    destroyInterstitialAd() {
      if (this.interAd !== undefined) {
        this.interAd.destroy();
        this.interAd = undefined;
      }
    },

    /**
     * 播放
     */
    playVideo() {
      const { currentVideo } = this.data;
      if (currentVideo !== false && this.pm) {
        if (currentVideo.is_unlock === 0) {
          this.pm.setPlayStatus('play');
        }
      }

    },

    /**
     * 金币解锁
     */
    coinUnlockPlaylet(){
      const { currentVideo,currentAblum } = this.data;
      const _this = this;

      if (currentVideo === false || currentAblum === false) {
        return;
      }

      os.showLoading({
        title: '请稍候...',
        mask: true
      });
      api.coinUnlockPlaylet({
        chapter_id: currentVideo.chapter_id,
        playlet_id: currentVideo.playlet_id,
      }).then(res => {
        os.hideLoading({});
        if (res.code == 201) {
          if (app.isCanBuy()) {
            app.Tips({title: `金币余额不足`});
          }
          this.openCustomDialog(1, currentVideo);
          return;
        }
        if (res.code == 200) {
          this.updateUnlockVideo(1);
          this.sendAppLogs('video', 14, {
            method_amount: currentAblum.gold_coin,
            method_mark: 1
          });
          return app.Tips({title: '解锁成功'});
        }else{
          return app.Tips({title: `解锁失败`, icon: "fail"});
        }
      }).catch(err => {
        os.hideLoading({});
      });
    },

    /**
     * 更新解锁状态
     * @param unlockType 0=广告解锁，1=金币解锁，2=会员，3=剧卡,4=广告挽留解锁
     * @param unlockNum  解锁集数(unlockType=4可用)
     */
    updateUnlockVideo(unlockType = 0, unlockNum = 1){
      let { currentVideo, currentAblum} = this.data;
      if (currentVideo === false || currentAblum === false) {
        return;
      }
      let allVideoData = currentAblum.list;
      let unlockIds = [];

      if (unlockType === 0) {
        unlockNum = parseInt(currentAblum?.ad_unlock_num || 1);
      }

      if (unlockType === 0 || unlockType === 4) {
        unlockIds = unlockEpisode(allVideoData, currentVideo.chapter_id, unlockNum - 1);
      }

      if (unlockType === 2 || unlockType === 3) {
        allVideoData.forEach((item, index) => {
          if (item.is_unlock === 1) {
            item.is_unlock = 0;
          }
        });
      }
      
      currentAblum.list = allVideoData;
      currentVideo.is_unlock = 0;
      
      app.playerData.currentAblum = currentAblum;
      this.data.currentAblum = currentAblum;
      this.data.currentVideo = currentVideo;

      if (unlockType === 0 || unlockType === 4) {
        app.Tips({title: `恭喜你成功解锁${unlockIds.length}集`});
        api.advertUnlockPlaylet({
          chapter_ids: unlockIds.join(','), 
          playlet_id: currentVideo.playlet_id,
          ad_id: app.globalData.currentAdConf?.advert_id || 0
        }, {showErr: false}); // 保存解锁状态

        // 挽留次数统计
        if (unlockType === 4) {
          api.getRetainNum({
            chapter_id: currentVideo?.chapter_id || 0,
            playlet_id: currentVideo?.playlet_id || 0,
          },{showErr: false});
        }

        unlockIds.forEach((item, index) => {
          let cVideo = allVideoData?.find(i => i.chapter_id == item);
          this.sendAppLogs('video', 14, {
            method_cid: cVideo?.num || 0,
            method_amount: 0,
            method_mark: 3
          }); 
        });
      }

      if (unlockType === 1) {
        this.pm.setCurrentUnlock();
        return;
      }
      
      this.refreshChapterUnlock();
    },

    /**
     * 更新追剧状态
     */
    updateCollectUpdated(res) {
      let currentAblum = this.data.currentAblum;
      currentAblum.is_collect = res.is_collect;
      currentAblum.collect_id = res.collect_id;
      Object.assign(app.playerData.currentAblum, currentAblum);
      Object.assign(this.data.currentAblum, currentAblum);
      db.updateSeenHistoryLogs(currentAblum.playlet_id, res);
    },

    /**
     * 刷新剧集
     */
    refreshChapterData() {
      const _this = this;
      const { currentAblum } = app.playerData;
      const album_id = parseInt(this.option?.tt_album_id || 0);
      
      if (currentAblum !== false) {
        if (currentAblum.album_id == album_id) {
          _this.setCurrentVideo(currentAblum);
          return;
        }
      }
      if (this.isLoadData) {
        return;
      }
      const data = {
        success: function(res){
          _this.isLoadData = false;
          _this.setCurrentVideo(res);
        },
        fail: function() {
          _this.isLoadData = false;
          if (_this.pm) {
            _this.pm.setPlayStatus('pause') // 暂停
          }
          app.Tips({title: `剧集已下架~`, icon: "fail"}, {tab: 1, url:'/pages/index/index'});
        }
      };
      this.isLoadData = true;
      Object.assign(this.option, data);
      app.getChapterList(this.option);
    },

    /**
     * 设置当前剧集
     */
    setCurrentVideo(res) {
      const _this = this;
      this.data.currentAblum = res;
      this.option.playlet_id = res.playlet_id;
      app.playerData.currentAblum = res;
      this.refreshChapterUnlock();
      
      // 免费-混合付费
      this.data.iaaMix = (res?.iaa_mix || 0) == 1 ? true:false;
      // this.data.iaaMix = true;
      app.globalData.iaaMix = this.data.iaaMix;
     
      // 长按倍速观看引导
      setTimeout(function(){
        if (_this.isPlay) {
          if (db.get('show_longspeed_tips') !== 1) {
            _this.openCustomDialog(4);
          }
        }
      }, 10000);

      if (this.pm) {
        this.bindUnlockPreview();
        
        // 倍速设置
        this.pm.setConfig({
          showLockPage: app.globalData.appType === 1 ? false:true,
          playbackRate: parseFloat(res?.player_speed || 1)
        });

        // 完播推荐
        const albumId = res.recommend_playlet?.album_id || "";
        if (albumId !== "") {
          this.pm.setRecommendConfig({
            entryType: 1 ,
            switchStatus: true,
            data:{
              albumId: albumId,
              seq: 1
            }
          });
          Object.assign(this.data.fromPlayletData, {
            albumId: res.album_id,
            playletId: res.playlet_id,
            rAlbumId: albumId
          });
        } 

        this.pm.getPlayletInfo().then(ret => {
          Object.assign(_this.data, ret);
          this.getCurrentVideo(ret.seq);
          _this.sendAppLogs('app', 3);
        });
      }
    },
      
    /**
     * 刷新剧集解锁数据
     */
    refreshChapterUnlock() {
      const currentAblum = this.data.currentAblum;
      let free_num = (currentAblum?.free_chapter || 11) - 1;

      function getSerialNoGroup(arr) {
        let result = [];
        if (arr.length === 0) {
          return result;
        }
        for(let i = 0; i < arr.length; i++) {
          if (i === 0 || arr[i].is_unlock !== arr[i - 1].is_unlock) {
            let temp = {
              start: arr[i].num,
              end: arr[i].num,
              status: arr[i].is_unlock
            };
            result.push(temp);
          } else {
            result[result.length - 1].end = arr[i].num;
          }
        }
        return result;
      }

      let serialList = getSerialNoGroup(currentAblum?.list || []);
      let unlockList = [];
      let lockList = [];
      
      serialList.forEach(item => {
        let uList = {
          start_episode_no: item.start,
          end_episode_no: item.end
        };
        if (item.status === 0) {
          unlockList.push(uList);
        } else {
          lockList.push(uList);
        }
      });

      let data = {
        freeList: [{ 
          start_episode_no: 1,
          end_episode_no: free_num
        }]
      }

      if (unlockList.length > 0) {
        unlockList[0].start_episode_no = free_num + 1;
        Object.assign(data, {
          unlockList: unlockList
        });
      }

      if (lockList.length > 0) {
        Object.assign(data, {
          lockList: lockList
        });
      }

      app.echo('lockList: ', data);

      this.pm.setCatalog(data);
    },

    /**
     * 当前剧集信息
     * @param seq 当前集
     * @returns Object
     */
    getCurrentVideo(seq = 0) {
      const { currentTime, duration,currentAblum,fromPlayletId } = this.data;

      if (seq > 0) {
        this.data.seq = parseInt(seq);
      }

      if (this.data.seq <= 0) {
        this.data.seq = 1;
      }

      if (currentAblum === false) {
        app.playerData.currentVideo = this.data.currentVideo;
        return this.data.currentVideo;
      }

      let currentVideo = currentAblum.list.find(item => item.num === this.data.seq);
      if (currentVideo === undefined) {
        app.playerData.currentVideo = this.data.currentVideo;
        return this.data.currentVideo;
      }

      Object.assign(currentVideo, {
        currentTime: parseInt(currentTime),
        duration: parseInt(duration),
        follow: currentAblum?.follow || 3,
        fromPlayletId: fromPlayletId,
        is_collect: currentAblum.is_collect || 0,
        collect_id: currentAblum.collect_id || 0,
        playlet_name: currentAblum.playlet_name || '',
        iaa_mix: currentAblum?.iaa_mix || 0,
        gold_coin: currentAblum.gold_coin || 0
      });

      this.data.currentVideo = currentVideo;
      app.playerData.currentVideo = this.data.currentVideo;
      app.echo('currentVideo: ', this.data.currentVideo)
      return this.data.currentVideo;;
    },

    getMethodData(){
      const currentVideo = this.getCurrentVideo();
      return {
        method_id: currentVideo?.playlet_id || 0, 
        method_cid: currentVideo?.num || 0,
        method_amount: currentVideo?.currentTime || 0
      };
    },

    /**
     * 添加看过
     */
    andSeenPlaylet() {
      const { currentVideo, currentAblum } = this.data;
      if (currentVideo !== false) {
        if(this.data?.lastSeenSeq != currentVideo.num){
          const logsData = JSON.stringify(app.getLogsData(2, {
            method_id: currentVideo.playlet_id, 
            method_cid: currentVideo.num
          }));

          this.data.lastSeenSeq = currentVideo.num;
          // api.addCollect({
          //   playlet_id: currentVideo.playlet_id, 
          //   chapter_id: currentVideo.chapter_id,
          //   last_num: currentVideo.num, 
          //   logs_data: logsData,
          //   type: 0
          // }, {showErr: false});

          db.addSeenHistoryLogs({
            id: currentAblum.playlet_id, 
            playlet_id: currentAblum.playlet_id, 
            playlet_name: currentAblum.playlet_name, 
            chapter_id: currentVideo.chapter_id,
            total_num: currentAblum.total_num, 
            last_num: currentVideo.num, 
            num: currentVideo.num, 
            is_collect: currentAblum.is_collect,
            collect_id: currentAblum.collect_id, 
            cover_img: currentAblum.cover_img
          });

          this.sendAppLogs('video', 1);
        }
      }
    },

    /**
     * 发送日志
     */
    sendAppLogs(logType = 'app', markType = 1, data = {}){
      const { currentVideo,currentAblum } = this.data;
      if (currentVideo === false || currentAblum === false) {
        return;
      }

      if (logType === 'video' &&  (markType === 1 || markType === 4 || markType === 3)) {
        if (currentVideo.is_unlock == 1) {
          return;
        }
      }

      let rData = {
        method_id: currentVideo.playlet_id, 
        method_cid: currentVideo.num,
        method_rid: parseInt(currentVideo?.fromPlayletId || 0),
        method_amount: currentVideo.currentTime || 0
      };

      if (logType === 'iaa') {
        rData.method_amount = 0;
        rData.method_mark = '';
      }

      if(logType === 'video'){
        rData.method_amount = currentVideo.duration || 0;
        rData.method_mark = currentVideo.currentTime || '';

        if (markType == 2 || markType == 1) {
          rData.method_mark = currentVideo.is_unlock == 1 ? 3:1;
          rData.method_amount = currentVideo.currentTime || 0;
        }

        if (markType == 1 && rData.method_amount > 1) {
          // return;
        }

        if (markType == 5 && rData.method_amount <= 1) {
          // return;
        }

      }

      Object.assign(rData, data);
      app.sendAppLogs(logType, markType, rData);
    },

    /**
     * 检查是否有设置返回首页挽留弹框设置
     */
    checkAndSetBackAd() {
      const { currentAblum } = this.data;
      const backSwitch = currentAblum?.back_ad_switch || false;
      const list = currentAblum?.list || [];
      if (backSwitch === false || list.length === 0) {
        return;
      }
      const hasLockedEpisode = list.some(item => item.is_unlock === 1);
      if (hasLockedEpisode) {
        app.backAdData = this.data;
      }
    },

    /**
     * 卸载页面
     */
    onUnload: function () {
      clearInterval(this.playTimerId);
      clearInterval(this.initTime);

      this.checkAndSetBackAd();

      app.eventer.off('onRechargeSuccess');
      app.eventer.off('onRechargeCancel');
      app.eventer.off('onPopCancel');
      app.eventer.off('onPopSuccess');
      app.eventer.off('onAdUnlockEvent');
      app.eventer.off('onPlayerPageEvent');

      app.playerData.currentAblum = false;
      app.playerData.currentVideo = false;
      app.globalData.showAdNum = 0;

      this.destroyInterstitialAd();

      // 保存最后观看历史
      if (app.globalData.appType === 1) {
        db.saveLastSeenHistory(this.data.currentAblum);
      }

      this.sendAppLogs('video', 13, {
        appPath: "pages/player/player"
      });
    }
  },
});